﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using Sokoban.ViewModel;
using Sokoban.ViewModel.Boxes;
using Sokoban.Model;

namespace Sokoban
{
    /// <summary>
    /// Interaction logic for EditorWindow.xaml
    /// </summary>
    public partial class EditorWindow : Window
    {
        // enum?
        // 0 - Barrier
        // 1 - Empty
        // 2 - Box
        // 3 - Goal
        // 4 - Player

        EditorViewModel evm;
        int gridTool = 0;
        int rows;
        int cols;
        private void gridControl_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            if (menuItem == null)
            {
                return;
            }

            gridPlayer.FontWeight = FontWeights.Normal;
            gridBarrier.FontWeight = FontWeights.Normal;
            gridEmpty.FontWeight = FontWeights.Normal;
            gridBox.FontWeight = FontWeights.Normal;
            gridGoal.FontWeight = FontWeights.Normal;
            menuItem.FontWeight = FontWeights.Bold;
            gridTool = int.Parse(menuItem.Tag.ToString());
            // - - -
            Menu.Tag = menuItem.Header;
        }        
        public EditorWindow()
        {
            InitializeComponent();
        }
        private void CreateButtonGrid()
        {
            menuSave.IsEnabled = false;
            ButtonGrid.Children.Clear();
            ButtonGrid.ColumnDefinitions.Clear();
            ButtonGrid.RowDefinitions.Clear();

            evm = new EditorViewModel(rows, cols);
            this.DataContext = evm;

            for (int i = 0; i < rows; i++)
            {
                RowDefinition rowDef = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
                ButtonGrid.RowDefinitions.Add(rowDef);
            }

            for (int j = 0; j < cols; j++)
            {
                ColumnDefinition colDef = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
                ButtonGrid.ColumnDefinitions.Add(colDef);
            }

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    Button b = new Button();
                    b.HorizontalAlignment = HorizontalAlignment.Stretch;
                    b.VerticalAlignment = VerticalAlignment.Stretch;
                    b.Name = "button" + i;
                    b.Tag = i + "," + j;
                    b.Content = "Wall";
                    b.Click += new RoutedEventHandler(GridClick);
                                     
                    var textBinding = new Binding { Path = new PropertyPath("Name"), Source = evm.BoxMatrix[i, j] };
                    BindingOperations.SetBinding(b, Button.ContentProperty, textBinding);

                    //var colorBinding = new Binding { Path = new PropertyPath("BackgroundColor"), Source = evm.BoxMatrix[i, j] };
                    //BindingOperations.SetBinding(b, Button.BackgroundProperty, colorBinding);

                    var imgBindig = new Binding { Path = new PropertyPath("ImgSource"), Source = evm.BoxMatrix[i, j] };
                    BindingOperations.SetBinding(b, Button.BackgroundProperty, imgBindig);

                    var brush = new ImageBrush();
                    brush.ImageSource = new BitmapImage(new Uri(evm.BoxMatrix[i, j].ImgSource, UriKind.Absolute));
                    b.Background = brush;

                    ButtonGrid.Children.Add(b);
                    Grid.SetRow(b, i);
                    Grid.SetColumn(b, j);
                }
            }
        }
        private void GridClick(object sender, RoutedEventArgs e)
        {
            menuSave.IsEnabled = false;
            menuSolver.IsEnabled = false;
            if (Menu.Tag != null)
            {
                string tag = (sender as Button).Tag.ToString();
                int i = int.Parse(tag.Substring(0,tag.IndexOf(',')));
                int j = int.Parse(tag.Substring(tag.IndexOf(',')+1));
                if ((i!=0)&&(j!=0)&&(i!=rows-1)&&(j!=cols-1))
                    evm.GridClicked(Menu.Tag.ToString(),i, j);
                var brush = new ImageBrush();
                brush.ImageSource = new BitmapImage(new Uri(evm.BoxMatrix[i, j].ImgSource, UriKind.Absolute));
                (sender as Button).Background = brush;
            }                
        }
        private void menuNew_Click(object sender, RoutedEventArgs e)
        {
            View.Input inputbox = new View.Input();
            var result = inputbox.ShowDialog();
            if (result.HasValue && result.Value)
            {
                rows = int.Parse(inputbox.ComboRows.SelectedItem.ToString());
                cols = int.Parse(inputbox.ComboCols.SelectedItem.ToString());
                CreateButtonGrid();
            }
            EditorWindowForm.Height = rows * 70;
            if (EditorWindowForm.Height > System.Windows.SystemParameters.PrimaryScreenHeight)
                EditorWindowForm.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            EditorWindowForm.Width = cols * 70;
            if (EditorWindowForm.Width > System.Windows.SystemParameters.PrimaryScreenWidth)
                EditorWindowForm.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
        }
        private void menuLoad_Click(object sender, RoutedEventArgs e)
        {
            menuSave.IsEnabled = false;
            menuSolver.IsEnabled = false;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.InitialDirectory = Environment.CurrentDirectory;
            ofd.ShowDialog();
            if (!string.IsNullOrEmpty(ofd.SafeFileName))
            {
                var path = ofd.FileName;
                evm = new EditorViewModel();
                try
                {
                    evm.LoadMap(path);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Invalid map!");
                    return;
                }
            }

            //grid
            ButtonGrid.Children.Clear();
            ButtonGrid.ColumnDefinitions.Clear();
            ButtonGrid.RowDefinitions.Clear();

            //evm = new EditorViewModel(rows, cols);
            this.DataContext = evm;

            for (int i = 0; i < evm.Rows; i++)
            {
                RowDefinition rowDef = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
                ButtonGrid.RowDefinitions.Add(rowDef);
            }

            for (int j = 0; j < evm.Cols; j++)
            {
                ColumnDefinition colDef = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
                ButtonGrid.ColumnDefinitions.Add(colDef);
            }
            for (int i = 0; i < evm.Rows; i++)
            {
                for (int j = 0; j < evm.Cols; j++)
                {
                    Button b = new Button();
                    b.HorizontalAlignment = HorizontalAlignment.Stretch;
                    b.VerticalAlignment = VerticalAlignment.Stretch;
                    b.Name = "button" + i;
                    b.Tag = i + "," + j;
                    b.Content = "Wall";
                    b.Click += new RoutedEventHandler(GridClick);

                    var textBinding = new Binding { Path = new PropertyPath("Name"), Source = evm.BoxMatrix[i, j] };
                    BindingOperations.SetBinding(b, Button.ContentProperty, textBinding);

                    //var colorBinding = new Binding { Path = new PropertyPath("BackgroundColor"), Source = evm.BoxMatrix[i, j] };
                    //BindingOperations.SetBinding(b, Button.BackgroundProperty, colorBinding);

                    var imgBindig = new Binding { Path = new PropertyPath("ImgSource"), Source = evm.BoxMatrix[i, j] };
                    BindingOperations.SetBinding(b, Button.BackgroundProperty, imgBindig);

                    var brush = new ImageBrush();
                    brush.ImageSource = new BitmapImage(new Uri(evm.BoxMatrix[i, j].ImgSource, UriKind.Absolute));
                    b.Background = brush;

                    ButtonGrid.Children.Add(b);
                    Grid.SetRow(b, i);
                    Grid.SetColumn(b, j);
                }
            }
            EditorWindowForm.Height = evm.Rows * 70;
            if (EditorWindowForm.Height > System.Windows.SystemParameters.PrimaryScreenHeight)
                EditorWindowForm.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            EditorWindowForm.Width = evm.Cols * 70;
            if (EditorWindowForm.Width > System.Windows.SystemParameters.PrimaryScreenWidth)
                EditorWindowForm.Width = System.Windows.SystemParameters.PrimaryScreenWidth;

        }
        private void menuCheck_Click(object sender, RoutedEventArgs e)
        {
            //playercount==1 and ((goalCount > 0) && (goalCount <= boxCount))
            if ((evm.CheckPlayer()) && (evm.CheckBoxAndGoals()))
            {
                menuSave.IsEnabled = true;
                menuSolver.IsEnabled = true;
            }                        
            else
            {
                MessageBox.Show("Invalid Map!");
            }
        }
        private void menuSave_Click(object sender, RoutedEventArgs e)
        {
            evm.SaveMap();
        }
        private void menuClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void menuSolver_Click(object sender, RoutedEventArgs e)
        {
            if (evm.CheckMapSolvable())
                MessageBox.Show("This map can be solved!");
            else
                MessageBox.Show("This map can't be solved!");
        }



      

    }
}
